package com.duojuhe.coremodule.tracking.service.impl;

import com.duojuhe.cache.SystemDictCache;
import com.duojuhe.common.annotation.DataScopeFilter;
import com.duojuhe.common.bean.UserTokenInfoVo;
import com.duojuhe.common.constant.DataScopeConstants;
import com.duojuhe.common.exception.base.DuoJuHeException;
import com.duojuhe.common.result.ErrorCodes;
import com.duojuhe.common.result.PageResult;
import com.duojuhe.common.result.ServiceResult;
import com.duojuhe.common.utils.idgenerator.UUIDUtils;
import com.duojuhe.common.utils.page.PageHelperUtil;
import com.duojuhe.coremodule.BaseService;
import com.duojuhe.coremodule.system.entity.SystemDict;
import com.duojuhe.coremodule.tracking.entity.TrackingCode;
import com.duojuhe.coremodule.tracking.entity.TrackingProductSupplier;
import com.duojuhe.coremodule.tracking.mapper.TrackingCodeMapper;
import com.duojuhe.coremodule.tracking.mapper.TrackingProductSupplierMapper;
import com.duojuhe.coremodule.tracking.pojo.dto.trackingsupplier.*;
import com.duojuhe.coremodule.tracking.service.TrackingProductSupplierService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class TrackingProductSupplierServiceImpl extends BaseService implements TrackingProductSupplierService {
    @Resource
    private SystemDictCache systemDictCache;
    @Resource
    private TrackingCodeMapper trackingCodeMapper;
    @Resource
    private TrackingProductSupplierMapper trackingProductSupplierMapper;
    /**
     * 【查询所有产品供货商】产品供货商管理
     * @param req
     * @return
     */
    @DataScopeFilter
    @Override
    public ServiceResult<PageResult<List<QueryTrackingProductSupplierPageRes>>> queryTrackingProductSupplierPageResList(QueryTrackingProductSupplierPageReq req) {
        PageHelperUtil.orderByAndStartPage(req, "createTime desc, supplierId desc");
        List<QueryTrackingProductSupplierPageRes> list = trackingProductSupplierMapper.queryTrackingProductSupplierPageResList(req);
        for (QueryTrackingProductSupplierPageRes res:list){
            SystemDict dictStatus = systemDictCache.getSystemDictByDictCode(res.getStatusCode());
            res.setStatusName(dictStatus.getDictName());
            res.setStatusColor(dictStatus.getDictColor());
        }
        return PageHelperUtil.returnServiceResult(req, list);
    }

    /**
     * 【查询所有产品供货商】供前端选择产品供货商
     * @param req
     * @return
     */
    @DataScopeFilter(dataScope = DataScopeConstants.TENANT_ALL_DATA)
    @Override
    public ServiceResult<List<QuerySelectTrackingProductSupplierRes>> querySelectNormalTrackingProductSupplierResList(QuerySelectTrackingProductSupplierReq req) {
        PageHelperUtil.defaultOrderBy("createTime desc, supplierId desc");
        List<QuerySelectTrackingProductSupplierRes> list = trackingProductSupplierMapper.querySelectNormalTrackingProductSupplierResList(req);
        return ServiceResult.ok(list);
    }

    /**
     * 【保存】产品供货商
     * @param req
     * @return
     */
    @Override
    public ServiceResult saveTrackingProductSupplier(SaveTrackingProductSupplierReq req) {
        //当前登录用户
        UserTokenInfoVo userTokenInfoVo = getCurrentLoginUserInfoDTO();
        //检查供货商名称
        checkProductSupplierName(req.getSupplierName(),userTokenInfoVo.getTenantId());
        //供货商id
        String supplierId = UUIDUtils.getUUID32();
        //当前时间
        Date date = new Date();
        TrackingProductSupplier productSupplier = new TrackingProductSupplier();
        productSupplier.setSupplierId(supplierId);
        productSupplier.setSupplierName(req.getSupplierName());
        productSupplier.setSupplierNumber(UUIDUtils.getSequenceNo());
        productSupplier.setSupplierCode(req.getSupplierCode());
        productSupplier.setSort(req.getSort());
        productSupplier.setStatusCode(req.getStatusCode());
        productSupplier.setMobileNumber(req.getMobileNumber());
        productSupplier.setRemark(req.getRemark());
        productSupplier.setDescription(req.getDescription());
        productSupplier.setCreateTime(date);
        productSupplier.setUpdateTime(date);
        productSupplier.setCreateUserId(userTokenInfoVo.getUserId());
        productSupplier.setUpdateUserId(userTokenInfoVo.getUserId());
        productSupplier.setCreateDeptId(userTokenInfoVo.getCreateDeptId());
        productSupplier.setTenantId(userTokenInfoVo.getTenantId());
        trackingProductSupplierMapper.insertSelective(productSupplier);
        return ServiceResult.ok(supplierId);
    }


    /**
     * 【修改】产品供货商
     * @param req
     * @return
     */
    @Override
    public ServiceResult updateTrackingProductSupplier(UpdateTrackingProductSupplierReq req) {
        //供货商id
        String supplierId = req.getSupplierId();
        TrackingProductSupplier productSupplierOld = trackingProductSupplierMapper.selectByPrimaryKey(supplierId);
        if (productSupplierOld==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        if (!productSupplierOld.getSupplierName().equals(req.getSupplierName())){
            //检查供货商名称
            checkProductSupplierName(req.getSupplierName(),productSupplierOld.getTenantId());
        }
        //当前登录用户
        UserTokenInfoVo userTokenInfoVo = getCurrentLoginUserInfoDTO();
        //当前时间
        Date date = new Date();
        TrackingProductSupplier productSupplier = new TrackingProductSupplier();
        productSupplier.setSupplierId(supplierId);
        productSupplier.setSupplierName(req.getSupplierName());
        productSupplier.setSupplierCode(req.getSupplierCode());
        productSupplier.setStatusCode(req.getStatusCode());
        productSupplier.setMobileNumber(req.getMobileNumber());
        productSupplier.setRemark(req.getRemark());
        productSupplier.setDescription(req.getDescription());
        productSupplier.setUpdateTime(date);
        productSupplier.setSort(req.getSort());
        productSupplier.setUpdateUserId(userTokenInfoVo.getUserId());
        trackingProductSupplierMapper.updateByPrimaryKeySelective(productSupplier);
        return ServiceResult.ok(supplierId);
    }

    /**
     * 【删除】根据产品供货商ID删除产品供货商，注意一次仅能删除一个产品供货商，存在绑定关系的则不能删除
     * @param req
     * @return
     */
    @Override
    public ServiceResult deleteTrackingProductSupplierBySupplierId(TrackingProductSupplierIdReq req) {
        //供货商id
        String supplierId = req.getSupplierId();
        TrackingProductSupplier productSupplierOld = trackingProductSupplierMapper.selectByPrimaryKey(supplierId);
        if (productSupplierOld==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //检查是否关联了 防伪码
        checkRelationTrackingCode(supplierId);
        //供货商删除
        trackingProductSupplierMapper.deleteByPrimaryKey(supplierId);
        return ServiceResult.ok(supplierId);
    }

    /**
     * 【私有方法，辅助其他接口方法使用】 根据供货商id查询是否关联了防伪码
     */
    private void checkRelationTrackingCode(String supplierId) {
        if (StringUtils.isBlank(supplierId)){
            throw new DuoJuHeException(ErrorCodes.TRACKING_PRODUCT_SUPPLIER_RELATION_TRACKING_CODE_NOT_DELETE);
        }
        Example example = new Example(TrackingCode.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("supplierId", supplierId);
        if(trackingCodeMapper.selectByExample(example).size()>0){
            throw new DuoJuHeException(ErrorCodes.TRACKING_PRODUCT_SUPPLIER_RELATION_TRACKING_CODE_NOT_DELETE);
        }
    }


    /**
     * 【私有方法，辅助其他接口方法使用】 检查当前租户下面供货商是否已经存在
     */
    private void checkProductSupplierName(String supplierName,String tenantId) {
        if (StringUtils.isBlank(supplierName)||StringUtils.isBlank(tenantId)){
            throw new DuoJuHeException(ErrorCodes.TRACKING_PRODUCT_SUPPLIER_NAME_EXIST);
        }
        Example example = new Example(TrackingProductSupplier.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("supplierName", supplierName);
        criteria.andEqualTo("tenantId", tenantId);
        if(trackingProductSupplierMapper.selectByExample(example).size()>0){
            throw new DuoJuHeException(ErrorCodes.TRACKING_PRODUCT_SUPPLIER_NAME_EXIST);
        }
    }
}
